package com.tjetc.tcp.server;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class _2Server {
    /*
        1.编写⼀个服务端，和⼀个客户端
        2.服务器端在9999端⼝监听
        3.客户端连接到服务端，发送"hello,server",并接收服务器端回发的 "hello,client",再退出
        4.服务器端接收到客户端发送的信息，输出，并发送"hello,client",再退出

     */
    /*
        思路分析：
        1. 开放9999端口等待连接
        2. 获取输入流
        3. 从流中获取数据并输出
        4. 获取输出流
        5. 往输出流给出响应
     */

    public static void main(String[] args) {
        System.out.println("等待连接......");
        try (
                ServerSocket serverSocket = new ServerSocket(9999);
                Socket socket = serverSocket.accept();
                // 通过socket拿到输入流
                InputStream inputStream = socket.getInputStream();
                // 通过socket拿到输出流
                OutputStream outputStream = socket.getOutputStream();
        ) {
            System.out.println(socket);
            System.out.println("inputStream.getClass() = " + inputStream.getClass());
            System.out.println("outputStream.getClass() = " + outputStream.getClass());
            byte[] bytes = new byte[1024];
            int len = 0;
            while ((len = inputStream.read(bytes)) != -1) {
                System.out.println(new String(bytes, 0, len));
            }
            // 给客服端发送响应
            outputStream.write("hello, client".getBytes());
//            socket.shutdownOutput();

            System.out.println("服务器退出！");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
